<template>
  <div class="permission">
    <el-card>
      <div style="text-align: right">
        <el-button
          type="primary"
          size="small"
          @click="addClick('0', 1)"
        >添加菜单</el-button>
      </div>
      <el-table :data="list" row-key="id">
        <el-table-column label="菜单名称" prop="name" />
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="text"
              @click="addClick(row.id, 1)"
            >添加页面</el-button>
            <el-button
              type="text"
              @click="addClick(row.id, 2)"
            >添加按钮</el-button>
            <el-button type="text" @click="del(row.id)">删除</el-button>
            <el-button type="text" @click="edit(row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增弹框组件 -->
    <Add ref="add" @getData="getData" />
  </div>
</template>

<script>
// 导入新增弹框组件
import Add from './components/Add.vue'
// 导入权限相关接口
import { sysPermission, sysPermissionDelete } from '@/api/permission'
export default {
  components: {
    Add
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取权限函数
    async getData() {
      const res = await sysPermission()
      // console.log(res.data)
      // 将数据转换成树形结构
      this.list = this.changeData(res.data)
    },
    // 树形数据转换
    changeData(arr, str = '0') {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },

    // 添加菜单点击事件
    addClick(pid, type) {
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'add'
      this.$refs.add.form.pid = pid
      this.$refs.add.form.type = type
    },

    // 修改按钮点击事件
    edit(row) {
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'edit'
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    },

    // 删除按钮点击事件
    async del(id) {
      await sysPermissionDelete(id)
      this.$confirm('您确定要删除该权限吗?', '温馨提示')
        .then(() => {
          this.$message.success('删除权限成功')
          this.getData()
        })
        .catch()
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 15px;
}
</style>
